// pages/player/player.js
var _animation; // 动画实体
var _animationIndex = 0; // 动画执行次数index（当前执行了多少次）
var _animationIntervalId = -1; // 动画定时任务id，通过setInterval来达到无限旋转，记录id，用于结束定时任务
const _ANIMATION_TIME = 5000; // 动画播放一次的时长ms
Page({

  /**
   * 页面的初始数据
   */
  data: {
  bgmusic:'', //音频播放
  animation: '',
  state:false,
	url:'',
	name:'',
	starttime:"00:00",
	endtime:'00:00',
	scale:0,     //播放进度条
	duration:'',//总时长
	loop:false,  //判断是否开启循环,默认不开启
	timeing:[1,60,90], //定时器
	timeoutID:'', //定时器id
	path:'', //歌曲分类路径
	musiclist:[],  //歌曲列表
	index: '',  //当前播放歌曲下标
  },

  /**
   * 生命周期函数--监听页面加载
   */
  //毫秒转化成分钟秒
  getminsecd:function(time){
	 var m = Math.floor(time / 60 % 60);
	 var leftTime=time-m*60;
	 var s = Math.floor(leftTime  % 60);
	 if(m<10&&s<10){return '0'+m+':'+'0'+s}
	 else if(m>10&&s<10){return m+':'+'0'+s}
	 else if(m<10&&s>10){return '0'+m+':'+s}
	 else{return m+':'+s}
  },
  //拖动播放滑动条
  slidechange:function(e){
	  console.log(e);
	  this.setData({
		  scale:e.detail.value,
		 
	  });
	  var bgmusic = this.data.bgmusic
	  bgmusic.pause()
	  bgmusic.seek(this.data.duration*e.detail.value/100)
	   bgmusic.play()
  },
  //开启单曲循环
  cycle:function(){
	  var bgmusic = this.data.bgmusic;
	  if(this.data.loop){
		  wx.showToast({
		    title: '取消循环播放',
		    icon: 'none',
		    duration: 2000
		  })
		  this.setData({
			  loop:false
		  })
	  }else{
	  wx.showToast({
	    title: '开启循环播放',
	    icon: 'none',
	    duration: 2000
	  })
	  this.setData({
	  		loop:true
	  })
	  }
  },
  //设置定时器
  timing:function(){
	  var that=this;
	   var bgmusic = this.data.bgmusic;
	  console.log("设置定时器");
	  wx.showActionSheet({
	    itemList: ['30分钟', '60分钟', '90分钟'],
	    success (res) {
	      console.log(res.tapIndex)
		  var time=that.data.timeing[res.tapIndex]*60*1000;
		  var timeoutID=setTimeout(function() {
		           bgmusic.pause();
		        }, time);
			that.setData({
				timeoutID:timeoutID
			})
      wx.showToast({
        title: '设置成功,' + that.data.timeing[res.tapIndex]+'分钟后停止播放',
        icon:'none',
        duration:2000
      })
		  },
	    fail (res) {
	      console.log(res.errMsg)
	    }
	  })
  },
    //上一首
    previous:function(){
		console.log("上一首");
	   var bgmusic = this.data.bgmusic;
	   if(this.data.index>0){
		  var i=this.data.index-1;
		bgmusic.src=this.data.musiclist[i].url;
    bgmusic.title = this.data.musiclist[i].name;
		this.setData({
			index:i,
			url:this.data.musiclist[i].url,
			name:this.data.musiclist[i].name
		})
	   }else{
       console.log("回到最后一首");
       bgmusic.src = this.data.musiclist[this.data.musiclist.length - 1].url;
       bgmusic.title = this.data.musiclist[this.data.musiclist.length - 1].name;
       this.setData({
         index: this.data.musiclist.length-1,
         url: this.data.musiclist[this.data.musiclist.length - 1].url,
         name: this.data.musiclist[this.data.musiclist.length - 1].name
       })
	   }
	},
	//下一首
	next:function(){
		console.log("下一首");
		var bgmusic = this.data.bgmusic;
		if(this.data.index<this.data.musiclist.length-1){
				  var i=this.data.index+1;
				bgmusic.src=this.data.musiclist[i].url;
        bgmusic.title = this.data.musiclist[i].name;
				this.setData({
					index:i,
					url:this.data.musiclist[i].url,
					name:this.data.musiclist[i].name
				})
		}else{
      console.log("回到第一首");
      bgmusic.src = this.data.musiclist[0].url;
      bgmusic.title = this.data.musiclist[0].name;
      this.setData({
        index: 0,
        url: this.data.musiclist[0].url,
        name: this.data.musiclist[0].name
      })
	   }
	},
	
  onLoad: function (options) {
    const bgmusic = getApp().globalData.bgmusic;
    this.setData({
    bgmusic:bgmusic,
	  url:wx.getStorageSync('url'),
	  name:wx.getStorageSync('name'),
	  path:wx.getStorageSync('path'),
	  index:wx.getStorageSync('index'),
    })
    // //是否自动播放
    // bgmusic.autoplay = true;
    // //音乐播放地址
    // bgmusic.src = this.data.url
    // //是否循环播放
    // bgmusic.loop = false
    // //监听音频是否播放
    // console.log(bgmusic)
    // bgmusic.onPlay(() => {
		// console.log("开始播放");
		// var time = setTimeout(() => {
		//     bgmusic.currentTime
		//     bgmusic.onTimeUpdate(() => {
		//    //    console.log("总时长:"+bgmusic.duration)  //总时长
		// 	  // console.log("当前播放速度:"+bgmusic.currentTime)  //当前播放进度
		// 	  var alltime=this.getminsecd(bgmusic.duration);
		// 	  var nowtime=this.getminsecd(bgmusic.currentTime);
		// 	  this.setData({
		// 		  endtime:alltime,
		// 		  starttime:nowtime,
		// 		  scale:(bgmusic.currentTime/bgmusic.duration)*100,
		// 		  duration:duration,
		// 	  })
		//     });
    //   this.setData({
    //     state: true
    //   });
    //   var duration = bgmusic.duration;
		//   }, 500);
    // })
    // bgmusic.onPause(()=>{
		// console.log("停止播放");
    //   this.setData({
    //     state:false
    //   })
    // })
    // bgmusic.onError((res) => {
    //   console.log(res.errMsg)
    //   console.log(res.errCode)
    // })

  },
  play: function(){
    var bgmusic = this.data.bgmusic
    bgmusic.play()
    var time = setTimeout(() => {
      bgmusic.currentTime
      bgmusic.onTimeUpdate(() => {
        //    console.log("总时长:"+bgmusic.duration)  //总时长
        // console.log("当前播放速度:"+bgmusic.currentTime)  //当前播放进度
        var alltime = this.getminsecd(bgmusic.duration);
        var nowtime = this.getminsecd(bgmusic.currentTime);
        this.setData({
          endtime: alltime,
          starttime: nowtime,
          scale: (bgmusic.currentTime / bgmusic.duration) * 100,
          duration: duration,
        })
      });
      this.setData({
        state: true
      });
      var duration = bgmusic.duration;
    }, 500);
    //开始旋转
    this.startAnimationInterval()
  },
  pause: function(){
    this.data.bgmusic.pause()
    this.stopAnimationInterval()
  },

  onReady: function () {
    _animationIndex = 0;
    _animationIntervalId = -1;
    this.data.animation = ''; 
  },
  onUnload() {
    console.log('onUnload监听页面卸载');
  },
  onShow: function () {
    //请求获取歌曲列表
    var that = this;
    wx.request({
      url: getApp().globalData.baseurl + '/sleep-music/getname.php', //仅为示例，并非真实的接口地址
      data: {
        path: that.data.path,
      },
      method: 'GET',
      success(res) {
        console.log(res.data);
        var list = [];
        for (var i = 0; i < res.data.music.length; i++) {
          var index = res.data.music[i].indexOf(".");
          var name = res.data.music[i].substring(0, index);
          var obj = {
            name: res.data.name['' + name + ''],
            url: getApp().globalData.baseurl + '/sleep-music/' + that.data.path + '/' + encodeURI(res.data.music[i]),
          };
          list.push(obj);
          that.setData({
            musiclist: list
          });
        }
      }
    })
    // var that = this;
    // const db = wx.cloud.database();
    // var list = [];  //音频临时路径
    // var listurl = [];  //音频url路径
    // var musiclist = [];
    // db.collection(that.data.path).get({
    //   success(res) {
    //     console.log('查询成功', res.data);
    //     for (var i = 0; i < res.data.length; i++) {
    //       var obj = {
    //         name: res.data[i].name,
    //         url: '',
    //       };
    //       list.push(res.data[i].fileID);
    //       musiclist.push(obj);
    //     }
    //     wx.cloud.getTempFileURL({
    //       fileList: list,
    //       success: res => {
    //         for (var i = 0; i < res.fileList.length; i++) {
    //           listurl.push(res.fileList[i].tempFileURL);
    //         }
    //         for (var j = 0; j < listurl.length; j++) {
    //           musiclist[j].url = listurl[j]
    //         }
    //         console.log(musiclist);
    //         that.setData({
    //           musiclist: musiclist
    //         })
    //       },
    //       fail: err => {
    //         // handle error
    //       }
    //     })
    //   },
    //   fail: err => {
    //     console.log('失败')
    //   }
    // })
    const bgmusic = this.data.bgmusic;
    //音乐播放地址
    bgmusic.src = this.data.url;
    bgmusic.title=this.data.name;
    //监听音频是否播放
    console.log(bgmusic)
    bgmusic.onPlay(() => {
      console.log("开始播放");
      var time = setTimeout(() => {
        bgmusic.currentTime
        bgmusic.onTimeUpdate(() => {
          //    console.log("总时长:"+bgmusic.duration)  //总时长
          // console.log("当前播放速度:"+bgmusic.currentTime)  //当前播放进度
          var alltime = this.getminsecd(bgmusic.duration);
          var nowtime = this.getminsecd(bgmusic.currentTime);
          this.setData({
            endtime: alltime,
            starttime: nowtime,
            scale: (bgmusic.currentTime / bgmusic.duration) * 100,
            duration: duration,
          })
        });
        this.setData({
          state: true
        });
        var duration = bgmusic.duration;
      }, 500);
    })
    bgmusic.onPause(() => {
      console.log("停止播放");
      this.setData({
        state: false
      })
    })
    bgmusic.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
    //监听单曲播放结束
    this.data.bgmusic.onEnded(()=>{
      if(this.data.loop){
        this.data.bgmusic.src=this.data.url;
        this.data.bgmusic.title=this.data.name;
      }else{
        this.next();}
    });
	  
    _animation = wx.createAnimation({
      duration: _ANIMATION_TIME,
      timingFunction: 'linear', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
      delay: 0,
      transformOrigin: '50% 50% 0'
    })
  },

  /**
   * 实现image旋转动画，每次旋转 120*n度
   */
  rotateAni: function (n) {
    _animation.rotate(120 * (n)).step()
    this.setData({
      animation: _animation.export()
    })
  },

  /**
   * 开始旋转
   */
  startAnimationInterval: function () {
    var that = this;
    that.rotateAni(++_animationIndex); // 进行一次旋转
    _animationIntervalId = setInterval(function () {
      that.rotateAni(++_animationIndex);
    },  _ANIMATION_TIME); // 每间隔_ANIMATION_TIME进行一次旋转
  },

  /**
   * 停止旋转
   */
  stopAnimationInterval: function () {
    if (_animationIntervalId> 0) {
      clearInterval(_animationIntervalId);
      _animationIntervalId = 0;
    }
  }
})